package com.zhuoan.im.server.handler;

import com.zhuoan.im.server.command.Command;
import com.zhuoan.im.server.command.ImStatus;
import com.zhuoan.im.webapp.biz.FriendsApplyBiz;
import com.zhuoan.im.webapp.dao.model.reqbody.FriendsApplyBody;
import com.zhuoan.im.webapp.dao.model.respbody.FriendsApplyRespBody;
import org.apache.commons.lang3.StringUtils;
import org.jim.common.ImPacket;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbCmdHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.ChannelContext;

import javax.annotation.Resource;

/**
 * FriendsApplyReqHandler
 * 根据协议进入WsProtocolHandler
 *
 * @author weixiang.wu
 * @date 2018-10-12 16:22
 **/
@RestController
public class FriendsApplyReqHandler extends AbCmdHandler {

    private final static Logger logger = LoggerFactory.getLogger(FriendsApplyReqHandler.class);

    @Resource
    private FriendsApplyBiz friendsApplyBiz;


    @Override
    public org.jim.common.packets.Command command() {
        return org.jim.common.packets.Command.addAndGet(Command.FRIENDS_APPLY_REQ.getResMessage(), Command.FRIENDS_APPLY_REQ.getResCode());
    }

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) {

        // 1.判断是否已经登录
        if (channelContext.getUserid() == null) {
            return new ImPacket(org.jim.common.packets.Command.addAndGet(Command.FRIENDS_APPLY_RES.getResMessage(),
                Command.FRIENDS_APPLY_RES.getResCode()), JsonKit.toJsonBytes("请您先登录"));
        }

        // 2.必要参数校验
        FriendsApplyBody friendsApplyBody = JsonKit.toBean(packet.getBody(), FriendsApplyBody.class);
        if (StringUtils.isBlank(String.valueOf(friendsApplyBody.getApplyUserId())) &&
            StringUtils.isBlank(String.valueOf(friendsApplyBody.getAppliedUserId()))) {
            return new ImPacket(org.jim.common.packets.Command.addAndGet(Command.FRIENDS_APPLY_RES.getResMessage(),
                Command.FRIENDS_APPLY_RES.getResCode()), JsonKit.toJsonBytes("用户id不能为空"));
        }

        // 3.进行好友添加申请
        friendsApplyBiz.addUser(friendsApplyBody);

        // 4.好友信息申请成功返回
        FriendsApplyRespBody friendsApplyRespBody = new FriendsApplyRespBody(org.jim.common.packets.Command.addAndGet(Command.FRIENDS_APPLY_RES.getResMessage(), Command.FRIENDS_APPLY_RES.getResCode())
            , ImStatus.C10022);
        return new
            ImPacket(org.jim.common.packets.Command.addAndGet(Command.FRIENDS_APPLY_RES.getResMessage(), Command.FRIENDS_APPLY_RES.getResCode()),
//            JsonKit.toJsonBytes("自定义的命令处理器返回的信息内容")
            friendsApplyRespBody.toByte()
        );
    }


}
